import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { SQLiteObject, SQLite } from '@ionic-native/sqlite';
import { Platform } from 'ionic-angular';
/*
  Generated class for the SqliteHelperProvider provider.

  See https://angular.io/guide/dependency-injection for more info on providers
  and Angular DI.
*/
@Injectable()
export class SqliteHelperProvider {

  database:SQLiteObject;
  win_db:any;//h5环境下的数据库对象
  win:any=window;//window对象
  constructor(private sqlite:SQLite,private platform:Platform) {
   
  }
/**
 * 创建打开数据库
 */
  createOrOpenDb():Promise<any>{
    return new Promise<any>((reslove,reject)=>{
      if(this.isMobile()){
        this.sqlite.create({name:'park_data_3.db',location:'default'})
        .then((db:SQLiteObject)=>{
          this.database=db;
          //创建数据表sql语句
          this.createTable().then(res=>reslove(res),err=>reject(err));
        })
        .catch(e=>{
          console.error(e);
          reject(e);
        });
      }else{
        this.win_db=this.win.openDatabase('park_data_4.db','1.0','景区信息表',60*1024*1024);
        //创建数据表sql语句
        this.createTable().then(res=>reslove(res),err=>reject(err));
      }
    });
  }

/**
 * 创建数据表
 */
  createTable():Promise<any>{
    let sql:string='CREATE TABLE IF NOT EXISTS parks_lite(objectId TEXT,name TEXT,point TEXT)';
    return this.executeSql(sql,[]);
  }
/**
 * 执行sql语句
 * @param sql 
 * @param params 
 */
  executeSql(sql:string,params:Array<any>):Promise<any>{
    if(this.isMobile()){
      if(this.database){
        return this.execLoaclSql(sql,params);
      }
    }else{
      if(this.win_db){
        return this.execWebSql(sql,params);
      }
    }
    return new Promise(resolve=>resolve([]));
  }
/**
 * 执行基于本地的sqlite的sql语句
 * @param sql 
 * @param params 
 */
  private execLoaclSql(sql:string,params:Array<any>):Promise<any>{
    return this.database.executeSql(sql,params);
  }
/**
 * 执行基于web的sql语句
 * @param sql 
 * @param params 
 */
  private execWebSql(sql:string,params:Array<any>):Promise<any>{
    return new Promise((resolve,reject)=>{
      this.win_db.transaction(tx=>{
        tx.executeSql(sql,params,(tx,res)=>resolve(res),(tx,err)=>reject(err));
      },err=>reject(err));
    });
  }
  /**
   * 判断是否为真机环境
   */
  isMobile():boolean{
    return this.platform.is('mobile')&&!this.platform.is('mobileweb');
  }
}